<?php
namespace app\common\storage;

use app\common\redis\Redis;

use app\common\model\tyyh\User;
use app\common\model\tyyh\UserOpenid;

/**
 * 非直接读取数据库存储
 */
class Login extends Base {

	public function __construct() {
		$this->request = loader()->loadAny('request', 'Login');
	}

	public function openid2token($openid) {
		$route = $this->request->get_route();
		return md5($route . '_' . $openid);
	}

	//获取token
	public function get_token($options) {
		$route = $this->request->get_route();
		$options['login_type'] = $route;

		$openid = $options['openid'];
		$token = $this->openid2token($openid);
		$redis = Redis::factory();
		$redis->setArray($route . '_' . $token, $options, config('login.expires'));
		return $token;
	}

	//读取获取token时的存储的相关信息
	public function token2options($token = null) {
		$route = $this->request->get_route();
		if(!$token) {
			$token = $this->request->get_token();
		}
		$redis = Redis::factory();
		$options = $redis->getArray($route . '_' . $token);
		return $options;
	}

	//获取当前openid
	public function get_openid() {
		$options = $this->token2options();
		return $options['openid'];
	}

	//是否登陆
	public function isLogin() {
		$user = $this->getCurrentUser();
		return !empty($user);
	}

	//获取当前用户
	public function getCurrentUser($token = null) {
		$options = $this->token2options($token);
		if(!isset($options['unionid'])) {
			return [];
		}
		$unionid = $options['unionid'];
		$openidData = UserOpenid::factory()->where(['unionid' => $unionid])->find();
		if(!$openidData || !$openidData['uid']) {
			return [];
		}

		$routeTypeEnum = loadEnum('RouteType');
		$routeOptions = $routeTypeEnum->get_options();
		$loginType = $options['login_type'];
		$field = $routeOptions[$loginType];
		if($routeTypeEnum->is_miniprogram_route($loginType) && !$openidData[$field] && isset($options['openid'])) {
			$openidData->$field = $options['openid'];
			$openidData->save();
		}

		if($options['login_type'] == 'app') {
			return loadOnly('tyyh\\User')->find4username($options['username']);
		} 
		return User::factory()->find($openidData['uid']);
	}

	public function create4phone($phone) {
		$options = $this->token2options();
		$options['phone'] = $phone;
		UserOpenid::factory()->create4phone($options);
	}

	//刷新当前用户
	public function refresh() {
		return true;
	}

	//退出
	public function exit() {
		$route = $this->request->get_route();
		$token = $this->request->get_token();
		$options = $redis->del($route . '_' . $token);
	}
}